<?php

namespace Auth\Model;

use Zend\Db\Sql\Where;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
use Auth\Model\AbstractModel\TableAbstract;
use HVTC\HVTC;

class UsersTable extends TableAbstract{
	public function fetchAll(Select $select = null) {
		if ($select == null)
			$select = new Select ();
		$select->from ( $this->_tableName )->join("user_role", "users.id = user_role.user_id",array("user_role_id"=>"id"))
		->join("roles", "user_role.role_id= roles.id", array("role"=>"name"));
		$resultSet = $this->tablegateway->selectWith ( $select );
		$resultSet->buffer ();
		return $resultSet;
	}
	public function prepareSearch(\Zend\Db\Sql\Select &$select, $strSearch){
		$columns = array("users.id", "email", "birthday", "fullname", "passport", "users.description", "phone");
		$w = new Where();
		foreach($columns as $col){
			$w->like($col, "%".$strSearch. "%");
			$select->where($w->or);
		}
		return $select;
	}
	/**
	 * @return \Auth\Model\Users
	 */
	public function getModel($data = null){
		return parent::getModel($data);
	}
	public function getListUser(Select $select = null) {
		if ($select == null)
			$select = new Select ();
		$select->from ( $this->_tableName )->join("user_role", "users.id = user_role.user_id",array("user_role_id"=>"id"))
		->join("roles", "user_role.role_id= roles.id", array("role"=>"name"));
		$db = $this->getDbAdapter();
		$sql = new Sql($db);
		$data = $sql->prepareStatementForSqlObject($select)->execute();
		$users = array ();
		foreach ( $data as $user ) {
			$userData = $user;
			$users [] = $userData;
		}
		return $users;
	}
	public function isAdmin($email) {
		$user = $this->getUser ( $email );
		$userRoleTbl = $this->getServiceLocator ()->get ( 'AdminManage\Model\UserRoleTable' );
		if ($this->getUserRole ( $user ['data'] ['id'] ) == "admin") {
			return true;
		}
		return false;
	}
	public function getUserRole($userId) {
		$id = ( int ) $userId;
		$db = $this->getDbAdapter ();
		$sql = new Sql ( $db );
		$tbl = $this->getTableName ();
		$select = $sql->select ( array("u"=>$tbl ))
                      ->join ( array("ur"=>"user_role"), "u.id = ur.user_id" )
		              ->join (array("r"=>"roles"), "ur.role_id= r.id", "name" )
		              ->where ( "u.id = " . $userId );
		$rs = $sql->prepareStatementForSqlObject ( $select )->execute ();
		if ($rs->count () > 0) {
			$data = $rs->current ();
			$rs = array(
					"role_id" => $data['role_id'],
					"role" => $data['name'],
			);
			return $rs;
		}
		return false;
	}
	public function deleteUser($paramsId){
		if(is_array($paramsId)){
			$where = new Where();
			$where->in("id",$paramsId);
			$this->tablegateway->update(array("is_deleted" => "1"),$where);
		}else{
			echo $this->tablegateway->update(array("is_deleted" => "1"),array("id"=>$paramsId));
		}
	}
	
	public function undeleteUser($paramsId){
		if(is_array($paramsId)){
			$where = new Where();
			$where->in("id",$paramsId);
			$this->tablegateway->update(array("is_deleted" => "0"),$where);
		}else{
			echo $this->tablegateway->update(array("is_deleted" => "0"),array("id"=>$paramsId));
		}
	}
	public function disableUser($paramsId){
		if(is_array($paramsId)){
			$where = new Where();
			$where->in("id",$paramsId);
			$this->tablegateway->update(array("is_active" => "0"),$where);
		}else{
			echo $this->tablegateway->update(array("is_active" => "0"),array("id"=>$paramsId));
		}
	}
	
	public function deleteAvatar($userId){
		$id = (int)$userId;
		if($id > 0){
			//Get file
			$user = $this->getUser($id);
			if(strlen($user['data']['avatar']) > 0){
				$file = realpath(MEDIA_PATH."/users/avatar/" . $user['data']['avatar']);
				if(file_exists($file))
					unlink($file);
			}
			$this->tablegateway->update(array("avatar"=>""),array("id"=>$id));
			return true;
		}
		return false;
	}
	
	public function activeUser($paramsId){
		if(is_array($paramsId)){
			$where = new Where();
			$where->in("id",$paramsId);
			return $this->tablegateway->update(array("is_active" => "1"),$where);
		}else{
			return $this->tablegateway->update(array("is_active" => "1"),array("id"=>$paramsId));
		}
	}
	
	public function listUsers() {
		$db = $this->getDbAdapter ();
		$colSelectUser = array (
				"id",
				"email",
				"fullname",
				"phone",
				"description",
				"sex",
				"birthday",
				"passport",
				"created_time",
				"modified_time",
				"last_logined",
				"creator_id",
				"modifier_id",
				"is_active",
				"is_deleted",
		);
		$sql = new Sql ( $db );
		$select = $sql->select ( "user_role" )->join ( $this->getTable (), "users.id=user_role.user_id", $colSelectUser )->join ( "roles", "roles.id = user_role.role_id", "name" );
		$results = $sql->prepareStatementForSqlObject ( $select )->execute ();
		$arr = array ();
		foreach ( $results as $result ) {
			$arr [] = $result;
		}
		return $arr;
	}
	public function getUser($userEmailOrId, $hasRole = false) { 
		if(is_numeric($userEmailOrId)){
			$rowset = $this->tablegateway->select(array('id' => $userEmailOrId));
		}
		else
			$rowset = $this->tablegateway->select(array('email' => $userEmailOrId));
		$row = $rowset->current(); 
		if(!$row){
			return array("error" => 1, "message" => sprintf("User <b>\"%s\"</b> not found", $userEmailOrId));
		}
		else{
			$data = $row->getData(); 
			if($hasRole){
				$role = $this->getUserRole($data['id']);
				$data['role'] = $role['role'];
				$data['role_id'] = $role['role_id'];
			}
			if($data['type'] === "team"){ 
				$teamTbl = $this->getServiceLocator()->get("Team\Model\TeamTable");
				$data['team'] = $teamTbl->loadByUser($data['id'])->getId();
			}
			$data['is_premium'] = 0;
			$pro_timestamp = strtotime($data['pro_expired_date']);
			if($pro_timestamp && $pro_timestamp > time()){
				$data['is_premium'] = 1;
			}else{
				//Set pro time to 0.
				$data['pro_expired_date'] = null;
				$this->getTablegateway()->update(array("pro_expired_date"=>""), array("id"=>$data['id']));
			}
			return array("error" => 0, "data" => $data);
		}
	}
	
	public function userExists($email) {
		$rowset = $this->tablegateway->select ( array (
				'email' => $email 
		) );
		$row = $rowset->current ();
		if (! $row) {
			return false;
		}
		return true;
	}
	public function isExist($email){
		return $this->userExists($email);
	}
	public function saveLoginTime(){
		$time = date("Y-m-d H:i:s", time());
		$ss = $this->getServiceLocator()->get("FEAuthService")->getStorage ()->read();
		$this->tablegateway->update(array("last_logined"=>$time),array("id"=>$ss['id']));
		return true;
	}
	private function prepareDataForUpdate(&$data){
		if(isset($data ['id']))
			$user = $this->getUser ( $data ['id'] );
		else if(isset($data ['email']))
			$user = $this->getUser ( $data ['email'] );
		if($user['error'] == 0){
			if($data['password'] == ""){
				unset($data['password']);
				unset($data['password_salt']);
			}
			if(strlen($data['avatar']) == 0)
				unset($data['avatar']);
			$data['modified_time'] = date("Y-m-d H:i:s",time());
			$ss = $this->getServiceLocator()->get("FEAuthService")->getStorage()->read();
			$data['modifier_id'] = $ss['id'];
			/* Remove all unnecessary fields for updating*/
			unset($data['creator_id']);
			unset($data['created_time']);
			unset($data['last_logined']);
			unset($data['is_active']);
			unset($data['is_deleted']);
			unset($data['token']);
			unset($data['token_time']);
			unset($data['balance']);
			unset($data['type']);
			return true;
		}
		return false;
	}
	
	public function GetIduserExists($email) {
		$rowset = $this->tablegateway->select ( array (
				'email' => $email
		) );
		$row = $rowset->current ();
	
		return $row->id;
	}
	public function save($userData) { 
		$data = ( array ) $userData; 
		if(isset($data['birthday']))
			$data['birthday'] = HVTC::formatDate($data['birthday']);
		$id = ( int ) $data ['id'];
		if (! $this->userExists ( $data ['email'] ) && $id == 0) {
			$data['created_time'] = date("Y-m-d H:i:s");
			$data['pro_expired_date'] = date("Y-m-d H:i:s");
			$data['modified_time'] = date("Y-m-d H:i:s");
			$data['last_logined'] = date("Y-m-d H:i:s"); 
			//echo aaa; exit;
			$this->tablegateway->insert ( $data );
			//echo aaa; exit;
			return $this->tablegateway->lastInsertValue;
		} else {
			if ($this->prepareDataForUpdate($data)) {
				$data['modified_time'] = date("Y-m-d H:i:s");
				echo $data ['email']; 
				$data['id'] =$this->GetIduserExists ( $data ['email'] );
				 $id = $data['id']; 
				$this->tablegateway->update ( $data, array("id" => $id) );
				return $id;
			} else {
				throw new \Exception ( 'User does not exist' );
			}
		}
	}
	
	public function checkUserInTeam($userId)
	{
		$userId = (int)$userId;
		$sql = new Sql($this->getDbAdapter());
		$select = $sql->select(array("u" => $this->getTableName()));
		$select->join(array('uit' => 'users_in_team'), "u.id = uit.user_id");
		$select->where(array('u.id' => $userId, 'u.is_active' => 1));
		$statement = $sql->prepareStatementForSqlObject($select);
		$result = $statement->execute()->count();
		if($result > 0)
			return true;
		return false;
	}
	// last login user
	
	public function LastLoginUser($paramsId,$today){
			return $this->tablegateway->update(array("last_logined" => $today),array("id" => $paramsId));
	}
	
	public function getFullnameByUserId($userId) {
		$userId = (int)$userId;
		$sql = new Sql($this->getDbAdapter());
		$select = $sql->select(array("u" => $this->getTableName()))->columns(array('fullname'));
		$select->where(array('id' => $userId));
		$fullname =  $sql->prepareStatementForSqlObject($select)->execute()->current();
		return $fullname['fullname'];
	}
	

	
	public function getEmailUsersDayLeft($day) {
		$sql = new Sql($this->getDbAdapter());
		$select = $sql->select(array("u" => $this->getTableName()))->columns(array('email','fullname'));
		$select->where("DATEDIFF(pro_expired_date,CURRENT_DATE()) = {$day}");
		$resultSet = $sql->prepareStatementForSqlObject($select)->execute();
		$result = array();
		foreach($resultSet as $row) {
			$result[] = $row;
		}
		return $result;
	}
}